package com.suliao.common.util;

import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author ：M1nG
 * @date ：Created in 2021/1/4 18:46
 * @description：
 * @version: 1.0
 */
@Component
public class RocketMQUtil  {

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    public RocketMQTemplate getRocketMQTemplate() {
        return this.rocketMQTemplate;
    }

    /**
     * 发送同步消息
     *
     * @param topicName
     * @param data
     */
    public void sendMsg(String topicName, String data) {
        rocketMQTemplate.send(topicName, MessageBuilder.withPayload(data).build());
    }


    /**
     * 发送消息 带 key
     *
     * @param topicName
     * @param data
     */
    public void sendSyncMsg(String topicName, Object data, long key) {
        rocketMQTemplate.syncSend(topicName, data, key);
    }


    /**
     *  发送即发即失消息（不关心发送结果）
     *
     * @param topicName
     * @param data
     */
    public void sendMsgOneWay(String topicName, String data) {
        rocketMQTemplate.sendOneWay(topicName, MessageBuilder.withPayload(data).build());
    }


    /**
     *  发送顺序消息
     *
     * @param topicName
     * @param data
     */
    public void sendMsgOrder(String topicName, String data,String hashKey) {
        rocketMQTemplate.syncSendOrderly(topicName, data, hashKey);
    }

    /**
     *  发送异步消息
     *  <p>
     *  使用示例
     * RocketMQUtil.asyncSend(topicName, data, new SendCallback() {
     *     @Override
     *     public void onSuccess(SendResult sendResult) {
     *          //此处处理返回
     *          if(sendResult.sendResult()==SendStatus.SEND_OK){
     *                  //成功
     *          }else if
     *              。。。。
     *     }
     *
     *     @Override
     *     public void onException(Throwable e) {
     *          //此处处理异常
     *     }
     *  });
     *  </p>
     *
     * @param topicName
     * @param data
     */
    public void sendAsyncMsg(String topicName,String data,SendCallback sendCallback){
        rocketMQTemplate.asyncSend(topicName, MessageBuilder.withPayload(data).build(),sendCallback);
    }


}
